<?php

class orderController extends manageController {

    public function __construct() {
        if (!isset($_SESSION['zp_company']['islogin']) || empty($_SESSION['zp_company']['islogin'])) {
            Tools::AlertTxt('?md=company&cl=login&at=login', '请先登录');
            exit;
        }
    }


    public function orderlistAction() {
        $table = "orders";
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $func = (!empty($this->params['func'])) ? $this->params['func'] : '';
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;

        $order_status = (!empty($this->params['_order_status'])) ?  $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int) $this->params['_shop_no'] : '';                  # 配送门店
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ?  $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                    # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束
        $startdate1 = $startdate;
        $enddate1 = $enddate;


        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        if (empty($_corder)){
            $_corder=date('Y-m-d');
        }
        $sourceS = explode('-',$source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];
        //抓列表
        $where_fields = 'o.isdeleted = 0 ';
        if (!empty($order_status)  && $order_status != '-1') {
            $where_fields .= ' AND o.status='.($order_status-100).'';
        }else{
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= " AND o.shop_no like '%".$shop_no."%' ";
        }

        if (!empty($_express_type) && $_express_type !='no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no like '%".$_ph_no."%' ";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no like '%".$_order_no."%' ";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }



        # 下单时间  开始时间
        if (!empty($startdate) && empty($enddate)) {
            $enddate = date('Y-m-d',strtotime('+30 day',strtotime($startdate)));
        }


        # 结束时间
        if (!empty($enddate) && empty($startdate)) {
            $startdate = date('Y-m-d',strtotime('-30 day',strtotime($enddate)));
        }


        if (!empty($startdate) && !empty($enddate) ) {
            $_corderS = $startdate." 00:00:00";
            $_corderE = $enddate." 23:59:59";
            $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
        }

        if(empty($startdate) && empty($enddate)){
            if(!$_order_no && !$_ph_no){
                $startdate = $enddate = $startdate1 = $enddate1 = date('Y-m-d');
                $_corderS = $startdate." 00:00:00";
                $_corderE = $enddate." 23:59:59";
                $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
            }
        }
        $sql = "SELECT o.*,exp.express_fee,exp.express_order_no,exp.shop_express_no FROM orders as o left join xd_store as s ON o.shop_no = s.store_id left join orders_express as exp ON exp.ph_no = o.ph_no and exp.status = o.status WHERE $where_fields AND s.company_id = $CPCode";
//        echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }


        if($rsp_list){
            $epress = Data::$_express_type;
            foreach ($rsp_list as &$rspva) {
                foreach ($epress as $exk => $exp) {
                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
                        $rspva['express_type_name'] = $exp;
                    }
                }
            }
        }
        # 获取门店列表
        $sql = "SELECT id,store_id,storename FROM  xd_store  WHERE status != 0 AND isdeleted = 0 AND company_id = $CPCode"; # business_status = 不限制店铺状态
        $storeRes = $this->model->getAny($sql);
        if (!empty($storeRes)) {
            while ($row = mysqli_fetch_array($storeRes, MYSQLI_ASSOC)) {
                $storeLiist[] = $row;
            }
        }
        if($storeLiist && count($storeLiist) > 0){
            # 重构
            foreach ($storeLiist as $stoval){
                $storeLiists[$stoval['store_id']] = $stoval['storename'];
            }
        }
        $sourceLists =  $this->GetSources([]);
        $this->view->setVariable("startdate", $startdate1);
        $this->view->setVariable("enddate", $enddate1);
        $this->view->setVariable("sourceN", $sourceN);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("_order_status", ($order_status-100));
        $this->view->setVariable("_source", $sourceK);
        $this->view->setVariable("_shop_no", $shop_no);
        $this->view->setVariable("_express_type", $_express_type);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);

        $this->view->setVariable("sourceLists", $sourceLists);
        $this->view->setVariable("storeLiists", $storeLiists);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function orderlist_checkAction(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $OrderData = $this->model->getItemById($id,'orders');
        $where['and']['=']['ph_no'] = $OrderData['ph_no'];
        $orderInfo = $this->model->getItemByOther($where,'orders_express');
        if($orderInfo && count((array)$orderInfo)>0){
            foreach($orderInfo as &$r){
                unset($r['tip']);
                unset($r['tip_remark']);
                $where_tip = array('AND'=>array('='=>array('order_no' => $r['shop_express_no'],'shop_no' => $r['shop_no'],'status' => 1,'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where_tip, 'tip_list');
                if($data){
                    foreach($data as $k=>$t){
                        $r['tip'] += $t['price'];
                        $r['tip_remark'] .= isset($t['tip_remark']) ? '备注'.($k+1).':'.$t['tip_remark'] :''.' ';
                    }
                }
            }
        }
//        var_dump($orderInfo);die;
        $OrderData['tip'] = $orderInfo[0]['tip'];
        $OrderData['tip_remark'] = $orderInfo[0]['tip_remark'];
        $OrderData['shop_express_remark'] = $orderInfo[0]['shop_express_remark'];
        $OrderData['express'] = $orderInfo;

        $OrderData['express_fee'] = $orderInfo[0]['express_fee'];
        $OrderData['express_type'] = $orderInfo[0]['express_type'];
        $OrderData['express_courier'] = $orderInfo[0]['express_courier'];
        $OrderData['express_mobile'] = $orderInfo[0]['express_mobile'];
        $orderProductInfo = $this->model->getItemByOther($where,'orders_product');
        $OrderData['product'] = $orderProductInfo;
        $epress = Data::$_express_type;
        $_order_status = Data::$_order_status;

        # 门店修改地址
        $where = array('AND'=>array('='=>array('orders_id'=>$id,'createid' => $_SESSION['zp_manage']['store_id'])));
        $orderby = ['createdt'=>'asc'];
        $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);

        if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0){
            foreach($shop_delivery_address as $k => $sdd){
                if($k == 0){
                    $shop_delivery_address[$k]['old_receiver_name'] = $OrderData['receiver'];
                    $shop_delivery_address[$k]['old_receiver_tel'] = $OrderData['receiver_tel'];
                    $shop_delivery_address[$k]['old_receiver_address'] = $OrderData['receiver_address'];
                }else{
                    $shop_delivery_address[$k]['old_receiver_name'] = $shop_delivery_address[$k-1]['receiver_name'];
                    $shop_delivery_address[$k]['old_receiver_tel'] = $shop_delivery_address[$k-1]['receiver_tel'];
                    $shop_delivery_address[$k]['old_receiver_address'] = $shop_delivery_address[$k-1]['receiver_address'];
                }
            }
            rsort($shop_delivery_address);
            $OrderData['shop_delivery_address'] =  $shop_delivery_address;
            $OrderData['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $OrderData['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $OrderData['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
            $OrderData['distance'] = $shop_delivery_address[0]['distance'];
            $OrderData['lat'] = $shop_delivery_address[0]['lat'];
            $OrderData['lng'] = $shop_delivery_address[0]['lng'];
        }

        $where=array();
        $where['and']['=']['store_id'] = $OrderData['shop_no'];
        $shop_info = $this->model->getItemByOther($where,'xd_store');
        $shop_info=is_array($shop_info) && count($shop_info)>0?$shop_info[0]:array();
        $this->view->setVariable("shop_info", $shop_info);

        $where=array();
        $where['and']['=']['is_parent'] = 1;
        $company_info = $this->model->getItemByOther($where,'xd_company');
        if (!empty($company_info)){
            foreach($company_info as $key=>$value){
                unset($company_info[$key]);
                $company_info[$value['code']]=$value;
            }
        }
        $this->view->setVariable("company_info", $company_info);


        $this->view->setVariable("page", $page);
        $this->view->setVariable("order_status", $_order_status);
        $this->view->setVariable("express", $epress);
        $this->view->setVariable("rsp_list", $OrderData);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function order_delivery_infoAction(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $OrderExpressData = $this->model->getItemById($id,'orders_express');
        $where['and']['=']['shop_express_no'] = $OrderExpressData['shop_express_no'];
        $expressData = $this->model->getItemByOther($where,'express_data');

        $_express_type = Data::$_express_type;
        $OrderExpressData['express_data'] = $expressData;
        $OrderExpressData['express_type_data'] = $_express_type;
        echo json_encode($OrderExpressData);
    }


    /**
     * 异常订单
     */
    public function orderErrorListAction(){
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $page = (!empty($this->params['page'])) ? (int) $this->params['page'] : 1;

        $order_status = (!empty($this->params['_eorder_status'])) ? (int) $this->params['_eorder_status'] : '';         # 订单状态
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                           # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ?  $this->params['_order_no'] : '';                  # 订单号
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("_eorder_status", $order_status);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);

        //抓列表
        $where = 'o.isdeleted = 0  AND ';
        if (!empty($_ph_no)) {
            $where .= "op.ph_no like '%".$_ph_no."%' AND ";
        }

        if (!empty($_order_no)) {
            $where .= "op.order_no like '%".$_order_no."%' AND ";
        }

        if (!empty($order_status)) {
            $where .= 'o.status='.$order_status.'  AND ';
        }else{
            $where .= '(o.status=6 OR o.status=7)  AND ';
        }
        $where .= ' op.express_type = "self" ';
        $sql = "SELECT op.ph_no,op.push_response_data,op.status,op.express_type,op.id,op.shop_no,op.order_no,o.source,s.storename as shop_name FROM orders as o left join xd_store as s ON s.store_id = o.shop_no left join orders_express as op ON o.ph_no = op.ph_no WHERE $where AND s.company_id = ".$CPCode;
        $total_count = $this->model->getTotalCountByJoin($sql);
//        echo $sql;die;
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    public function orderErrorList_checkAction(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $exp_where['AND']['=']['id'] = $id;
        $OrderExpressData = $this->model->getItemByOther($exp_where,'orders_express');
        if($OrderExpressData && count((array)$OrderExpressData)>0){
            foreach($OrderExpressData as &$r){
                unset($r['tip']);
                unset($r['tip_remark']);
                $where_tip = array('AND'=>array('='=>array('order_no' => $r['shop_express_no'],'shop_no' => $r['shop_no'],'status' => 1,'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where_tip, 'tip_list');
                if($data){
                    foreach($data as $k=>$t){
                        $r['tip'] += $t['price'];
                        $r['tip_remark'] .= isset($t['tip_remark']) ? '备注'.($k+1).':'.$t['tip_remark'] :''.' ';
                    }
                }
            }
        }
        $where['AND']['=']['ph_no'] = $OrderExpressData[0]['ph_no'];
        $OrderDatas = $this->model->getItemByOther($where,'orders');
        $OrderData = $OrderDatas[0];
        $OrderData['tip'] = $OrderExpressData[0]['tip'];
        $OrderData['tip_remark'] = $OrderExpressData[0]['tip_remark'];
        $OrderData['shop_express_remark'] = $OrderExpressData[0]['shop_express_remark'];

        $OrderData['express'] = $OrderExpressData;
        $where['and']['=']['ph_no'] = $OrderData['ph_no'];
        $orderProductInfo = $this->model->getItemByOther($where,'orders_product');
        $OrderData['product'] = $orderProductInfo;
        # 门店修改地址
        $where = array('AND'=>array('='=>array('orders_id'=>$id,'createid' => $_SESSION['zp_manage']['store_id'])));
        $orderby = ['createdt'=>'desc'];
        $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);

        if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0){
            $OrderData['shop_delivery_address'] = $shop_delivery_address;
            $OrderData['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $OrderData['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $OrderData['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
        }

        $this->view->setVariable("page", $page);
        $this->view->setVariable("rsp_list", $OrderData);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function orderErrorList_check1Action(){
        $id = empty($this->params["id"]) ? '0' : (int) $this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int) $this->params["page"];
        $OrderData = $this->model->getItemById($id,'orders');
        $where['and']['=']['ph_no'] = $OrderData['ph_no'];
        $orderInfo = $this->model->getItemByOther($where,'orders_express');
        $OrderData['express'] = $orderInfo;
        $orderProductInfo = $this->model->getItemByOther($where,'orders_product');
        $OrderData['product'] = $orderProductInfo;

        $epress = Data::$_express_type;
        $_order_status = Data::$_order_status;
        $this->view->setVariable("page", $page);
        $this->view->setVariable("order_status", $_order_status);
        $this->view->setVariable("express", $epress);
        $this->view->setVariable("rsp_list", $OrderData);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 异常导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function Error_exportAction(){
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $order_status = (!empty($this->params['_order_status'])) ?  $this->params['_order_status'] : 0;         # 订单状态
        $_ph_no = (!empty($this->params['_ph_no'])) ?  $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
        if (!empty($_ph_no)) {
            $ph_no = "op.ph_no like '%".$_ph_no."%' AND ";
        }

        if (!empty($_order_no)) {
            $order_no = "op.order_no like '%".$_order_no."%' AND ";
        }

        if (!empty($order_status)) {
            $status = ' o.status='.$order_status ;
        }else{
            $status = ' (o.status=6 OR o.status = 7) ';
        }
        $where = 'o.isdeleted=0 AND '.$ph_no.' '.$order_no.' '.$status.' AND op.express_type = "self" group by op.ph_no order by op.updatedt desc';
        $Joinprders = "left join orders  as o ON o.ph_no = op.ph_no";
        $JoinStore = "left join xd_store  as s ON s.store_id = op.shop_no";
        $sql = "SELECT op.shop_delivery_address,op.shop_delivery_address, op.ph_no,op.push_response_data,op.status,op.express_type,op.shop_express_no,op.shop_delivery_time,op.shop_pickup_time,op.shop_goods_weight,op.express_courier,op.express_mobile,op.express_order_no,o.*  FROM orders_express as op $Joinprders $JoinStore WHERE s.company_id = $CPCode AND $where";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if(empty($rsp_list)) {
            Tools::AlertTxt('?md=company&cl=order&at=orderErrorList', '没有可汇出数据');
            exit;
        }else {
            # 订单商品清单
            foreach($rsp_list as &$o){
                $where = ['AND'=>['='=>['ph_no'=>$o['ph_no']]]];
                $o['product'] = $this->model->getItemByOther($where,'orders_product');

            }

            # 组装合并
            $NewRspList = [];
            foreach($rsp_list as $rsp){
                if($rsp['product']){
                    foreach($rsp['product'] as $p){
                        unset($p['status']);
                        unset($p['order_no']);
                        unset($rsp['product']);
                        $NewRspList[] = array_merge($rsp,$p);
                    }
                }else{
                    $NewRspList[] = $rsp;
                }
            }
            $epress = Data::$_express_type;
            foreach ($NewRspList as &$rspva) {
                foreach ($epress as $exk => $exp) {
                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
                        $rspva['express_type_name'] = $exp;
                    }
                }
            }
        }


//        echo '<pre>';
//        var_dump($rsp_list);die;
        $titles = array('序号', '订单编号', '订单来源', '订单清单', '数量', '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人', '收货地址', '派单单号',
            '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态', '操作时间','POS生成订单');
        $tableName = "订单列表";
        ob_get_clean();
        ob_start();
        echo "\xEF\xBB\xBF";
        echo implode("\t ,", $titles)."\n";
        if($NewRspList) {
            foreach ($NewRspList as $key => $row) {
                $seller_remarks = $id = preg_replace("/(\n)|(\t)|(,)|(，)/", '!', $row['seller_remarks']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['qty'] = $row['qty'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $row['customre_memo'];
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                if($row['shop_delivery_address']){
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                }else{
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['receiver_address'] = $row['receiver_address'];
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = Data::$_express_status[$row['status']];
                $exportIinfo['createdt'] = $row['createdt'];
                $exportIinfo['pos_no'] = $row['order_no'];

                echo implode("\t ,", $exportIinfo) . "\n";
            }
        }

//        die;
        header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
        header('Accept-Ranges:bytes');
        header('Content-Length:' . ob_get_length());
        header('Content-Type:text/csv');
        ob_end_flush();
        exit;
    }

    public function export_OLDAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID

        $order_status = (!empty($this->params['_order_status'])) ?  $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int) $this->params['_shop_no'] : '';                  # 配送门店
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ?  $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
        $_riders = (!empty($this->params['_riders'])) ? $this->params['_riders'] : '';                          # 骑手电话
        $_corder = (!empty($this->params['_corder'])) ? $this->params['_corder'] : '';                          # 下单时间
        $order_status += 100;
        $sourceS = explode('-',$source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];
        //抓列表
        $where_fields = 'o.isdeleted = 0  ';
        if (!empty($order_status)  && $order_status != '-1') {
            $where_fields .= ' AND o.status='.($order_status-100).'';
        }else{
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no='.$shop_no.'';
        }

        if (!empty($_express_type) && $_express_type !='no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }


        if (!empty($_corder)) {
            $_corderS = $_corder." 00:00:00";
            $_corderE = $_corder." 23:59:59";
            $where_fields .= " AND o.order_time > '$_corderS' AND o.order_time < '$_corderE'";
        }
        $sql = "SELECT  o.*,exp.express_courier,exp.express_mobile,exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time ,exp.shop_goods_weight,exp.express_order_no  FROM orders as o left join xd_store as s ON o.shop_no = s.store_id 
        left join (SELECT shop_delivery_address,orders_id,express_courier,express_mobile,ph_no,shop_express_no,shop_delivery_time,shop_pickup_time,shop_goods_weight,express_order_no FROM orders_express  where status < 6 ) as exp
        ON o.ph_no = exp.ph_no where  $where_fields AND s.company_id = $CPCode ";
//        echo $sql;
        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if($rsp_list){
            # 订单商品清单
            foreach($rsp_list as &$o){
                $where = ['AND'=>['='=>['ph_no'=>$o['ph_no']]]];
                $o['product'] = $this->model->getItemByOther($where,'orders_product');

            }

            # 组装合并
            $NewRspList = [];
            foreach($rsp_list as $rsp){
                if($rsp['product']){
                    foreach($rsp['product'] as $p){
                        unset($p['status']);
                        unset($p['order_no']);
                        unset($rsp['product']);
                        $NewRspList[] = array_merge($rsp,$p);
                    }
                }else{
                    $NewRspList[] = $rsp;
                }
            }
            $epress = Data::$_express_type;
            foreach ($NewRspList as &$rspva) {
                foreach ($epress as $exk => $exp) {
                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
                        $rspva['express_type_name'] = $exp;
                    }
                }
            }
        }

      if(empty($NewRspList)) {
          Tools::AlertTxt('?md=company&cl=order&at=orderlist', '没有可汇出数据');
          exit;
      }else {
        $titles = array('序号', '订单编号', '订单来源', '订单清单', '数量', '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人', '收货地址', '派单单号',
            '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态', '操作时间');
        $tableName = "订单列表";
        ob_get_clean();
        ob_start();
        echo "\xEF\xBB\xBF";
        echo implode("\t ,", $titles)."\n";

            foreach ($NewRspList as $key => $row) {
                $seller_remarks = $id = preg_replace("/(\n)|(\t)|(,)|(，)/", '!', $row['seller_remarks']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['qty'] = $row['qty'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $row['customre_memo'];
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                if($row['shop_delivery_address']){
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                }else{
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['createdt'] = $row['createdt'];
                echo implode("\t ,", $exportIinfo) . "\n";
            }
        }
//        die;
        header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
        header('Accept-Ranges:bytes');
        header('Content-Length:' . ob_get_length());
        header('Content-Type:text/csv');
        ob_end_flush();
        exit;
    }



    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }


    /**
     * 导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */

    public function exportAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $CPCode = $_SESSION['zp_company']['company_code'];  # 分司 ID
        $order_status = (!empty($this->params['_order_status'])) ?  $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int) $this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int) $this->params['_company_no'] : '';         # 分司
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ?  $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                          # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束


        $order_status += 100;
        $where_fields = "    o.isdeleted = 0 AND exp.isdeleted = 0 ";

        $where_fields = 'o.isdeleted = 0 ';


        if (!empty($order_status)  && $order_status != '-1') {
            $where_fields .= ' AND o.status='.($order_status-100).'';
        }else{
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= " AND o.shop_no like '%".$shop_no."%' ";
        }

        if (!empty($_express_type) && $_express_type !='no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no like '%".$_ph_no."%' ";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no like '%".$_order_no."%' ";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$source'";
        }


        //if (!empty($company_no)) {
            $where_fields .= " AND b.code = $CPCode";
        //}

        # 开始时间
        if (!empty($startdate) && empty($enddate)) {
            $enddate = date('Y-m-d',strtotime('+30 day',strtotime($startdate)));
        }


        # 结束时间
        if (!empty($enddate) && empty($startdate)) {
            $startdate = date('Y-m-d',strtotime('-30 day',strtotime($enddate)));
        }


        if (!empty($startdate) && !empty($enddate) ) {
            $_corderS = $startdate." 00:00:00";
            $_corderE = $enddate." 23:59:59";
            $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
        }
        if(empty($startdate) && empty($enddate)){
            if(!$_order_no && !$_ph_no) {
                $startdate = $enddate = date('Y-m-d');
                $_corderS = $startdate." 00:00:00";
                $_corderE = $enddate." 23:59:59";
                $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
            }
        }

         $total_count=0;
        $sql = "SELECT count(o.id) as count   FROM orders as o 
LEFT JOIN ( SELECT  max(id) id, ph_no FROM orders_express GROUP BY ph_no ) as temp ON o.ph_no = temp.ph_no 
LEFT JOIN orders_express as exp ON exp.id = temp.id 
LEFT JOIN xd_store as s ON o.shop_no = s.store_id 
LEFT JOIN xd_company as b ON s.company_id = b.code 
WHERE $where_fields ";


        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $total_count = $row['count'];
            }
        }

        $rsp_list=array();
        $number_page=500;
        $total_page=floor($total_count/$number_page)+1;

        for($page=1;$page<=$total_page;$page++) {
            $sql = "SELECT s.longitude,s.latitude,s.storename, exp.express_fee,exp.push_response_data,exp.order_no,exp.ph_no,exp.push_response_data,exp.status,exp.express_type,
exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time,exp.shop_goods_weight,exp.express_courier,exp.express_mobile,exp.tip,exp.tip_remark,exp.shop_express_remark,
exp.express_order_no,exp.shop_delivery_address,op.product_name, o.*  FROM orders as o 
LEFT JOIN ( SELECT  max(id) id, ph_no FROM orders_express GROUP BY ph_no ) as temp ON o.ph_no = temp.ph_no 
LEFT JOIN orders_express as exp ON exp.id = temp.id 
LEFT JOIN xd_store as s ON o.shop_no = s.store_id 
LEFT JOIN xd_company as b ON s.company_id = b.code 
LEFT JOIN (SELECT orders_id,group_concat(concat(product_name,'X',qty)) as product_name FROM orders_product GROUP BY orders_id) as op ON op.orders_id = o.id
WHERE $where_fields ";


            $offset = ($page - 1) * $number_page;
            $limit = ' LIMIT  ' . $offset . ', ' . $number_page . ' ';
            $sql .= $limit;

            $res = $this->model->getAny($sql);
            if (!empty($res)) {
                while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                    $rsp_list[] = $row;
                }
            }
        }
        if($rsp_list){
            foreach ($rsp_list as &$rlt){
                $distance = $rlt['distance'];
                $exp_res = json_decode($rlt['push_response_data'],true);
                if($rlt['express_type'] == 'self'){
                    $distance = $rlt['distance'];
                }elseif($rlt['express_type'] == 'sf'){
                    $distance = isset($exp_res['result'])? $exp_res['result']['delivery_distance_meter']:$rlt['distance'];
                }elseif($rlt['express_type'] == 'ss'){
                    $distance = isset($exp_res['data']) && count($exp_res['data'])>0? $exp_res['data'][0]['distanceTotal']:$rlt['distance'];
                }elseif($rlt['express_type'] == 'dd'){
                    $distance = isset($exp_res['result'])? $exp_res['result']['distance']:$rlt['distance'];
                }elseif ($rlt['express_type'] == 'jrd') {
                    $distance = isset($exp_res['result']) ? $exp_res['result']['address_distance'] : $rlt['distance'];
                }
                if($rlt['express_type'] != 'jrd'){
                    $rlt['distance'] = round($distance / 1000, 2);
                }else{
                    $rlt['distance'] = $distance;
                }
            }

        }

        if($rsp_list && is_array($rsp_list) && count($rsp_list) > 0) {
            $titles = array('序号', '门店名称','订单编号', '订单来源', '订单清单',  '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人','收货人手机号', '收货地址', '派单单号',
                '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态','距离', '运费','小费','渠道运费','小费备注','指派备注', '操作时间','POS生成订单');
            $tableName = $_SESSION['zp_company']['company_name'] ."_订单列表_".date('YmdHis');
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles)."\n";
            foreach ($rsp_list as $key => $row) {
                $seller_remarks = Tools::clearSymbolForCSV($row['seller_remarks']);
                $customre_memo = Tools::clearSymbolForCSV($row['customre_memo']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['storename'] = $row['storename'];
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $customre_memo;
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                $exportIinfo['receiver_tel'] = $row['receiver_tel'];

                if ($row['shop_delivery_address']) {
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                } else {
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = empty($row['status'])?'':Data::$_express_status[$row['status']];
                $exportIinfo['distance'] = ($row['distance']>0)?$row['distance'].'千米':'';
                $exportIinfo['express_fee'] = $row['express_fee'];
                $exportIinfo['tip'] = $row['tip'];
                $exportIinfo['pos_fee'] = $row['pos_fee'] > 0 ? $row['pos_fee'] : 0;
                $exportIinfo['tip_remark'] = $row['tip_remark'];
                $exportIinfo['shop_express_remark'] = $row['shop_express_remark'];
                $exportIinfo['createdt'] = $row['createdt'];
                $exportIinfo['pos_no'] = $row['order_no'];
                foreach($exportIinfo as $k=>$v){
                    $v=Tools::clearSymbolForCSV($v);
                    $exportIinfo[$k]=$v;
                }


                echo implode("\t ,", $exportIinfo) . "\n";
            }
            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            ob_end_flush();
            exit;

        }else{
            Tools::GoToPrev( '没有可汇出数据');
            exit;
        }


    }



    public function orders_delAction()
    {
        $page = (!empty($this->params['page'])) ? (int)$this->params['page'] : 1;
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int)$this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int)$this->params['_company_no'] : '';         # 分司
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                          # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束
        $startdate1 = $startdate;
        $enddate1 = $enddate;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $sourceS = explode('-', $source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];


        $store =  $this->GetStores([]);
        $CompanyLiists =  $this->GetCompanys([]);
        $sourceLists =  $this->GetSources([]);

        //抓列表
        $where_fields = 'o.isdeleted = 1 and o.status = 100 ';
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no=' . $shop_no . '';
        }

        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }
        if (!empty($company_no)) {
            $where = array("AND" => array("=" => array('company_id' => $company_no,'isdeleted' => 0)));
            $field = 'id,store_id,storename';
            $_store_list = $this->model->getAll($where, 'xd_store', '', $field);
            $_q_stores=array();
            if(!empty($_store_list)){
                foreach($_store_list as $value){
                    $_q_stores[]=" o.shop_no='".$value['store_id']."' ";
                }
                $where_fields .= " AND (".join(" OR ",$_q_stores) .")";
            }else{
                $where_fields .= " AND o.shop_no='".$company_no."' ";   //没有门店，SQL执行后空值
            }
        }

        $left = "left join orders_express as d ON o.ph_no = d.ph_no and o.status = d.status";
        $sql = "SELECT o.*,d.express_fee ,d.express_order_no,d.shop_express_no FROM orders as o $left  WHERE $where_fields  ORDER BY o.id DESC ";

//         echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $company_id = $store['store_data'][$row['shop_no']]['company_id'];
                $row['name'] = $CompanyLiists[$company_id];
                $rsp_list[] = $row;
            }
        }

//        echo '<pre>';
//        var_dump($rsp_list);

        $this->view->setVariable("_company_no", $company_no);
        $this->view->setVariable("_source", $sourceK);
        $this->view->setVariable("sourceN", $sourceN);
        $this->view->setVariable("_shop_no", $shop_no);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);
        $this->view->setVariable("startdate", $startdate1);
        $this->view->setVariable("enddate", $enddate1);
        $this->view->setVariable("CompanyLiists", $CompanyLiists);
        $this->view->setVariable("sourceLists", $sourceLists);
        $this->view->setVariable("storeLiists", $store['storeLiists']);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

}